﻿using UnityEngine;

[ExecuteInEditMode]
public class FX_UVscroll : MonoBehaviour
{
	public int targetMaterialSlot = 0;

	public AnimationCurve AxisX = AnimationCurve.Linear( 0, 0, 1, 0 );
	public AnimationCurve AxisY = AnimationCurve.Linear( 0, 0, 1, 0 );
	public float MaxTime = 1f;

	private float _cur_time;

	protected ParticleSystemRenderer ps;

	void Awake()
	{
		CheckVersion();
		_cur_time = 0f;
		ps = transform.GetComponent<ParticleSystemRenderer>();
	}

	protected virtual void Update()
	{
		var y = _cur_time / MaxTime;

		if( _cur_time > MaxTime )
			_cur_time -= MaxTime;

		if( Application.isPlaying )
			renderer.materials[targetMaterialSlot].SetTextureOffset( "_MainTex", new Vector2( AxisX.Evaluate( y ), AxisY.Evaluate( y ) ) );
		_cur_time += Time.deltaTime;
	}

	// old_version
	#region Old_Version
	public float speedY = float.MaxValue * .5f;
	public float speedX = float.MaxValue * .5f;

	public void CheckVersion()
	{
		const float default_value = float.MaxValue * .5f;

		if( !speedX.Equals( default_value ) )
		{
			var target = speedX > 0 ? 1 : speedX < 0 ? -1 : 0;
			MaxTime = 1 / ( Mathf.Abs( speedX ) > 0f ? Mathf.Abs( speedX ) : 1f );
			AxisX = AnimationCurve.Linear( 0, 0, 1, target );
			speedX = default_value;
		}

		if( !speedY.Equals( default_value ) )
		{
			var target = speedY > 0 ? 1 : speedY < 0 ? -1 : 0;
			MaxTime = 1 / ( Mathf.Abs( speedY ) > 0f ? Mathf.Abs( speedY ) : 1f );
			AxisY = AnimationCurve.Linear( 0, 0, 1, target );
			speedY = default_value;
		}
	}
	#endregion
}
